<?php
namespace app\user\model;

use think\Model as ThinkModel;
use think\facade\Db;
use think\facade\Log;

/**
 * 项目模型
 * @package app\user\model
 */
class CommonUser extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'common_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 添加或获取微信用户
     *
     * @param array $user
     * @return array|false
     */
    public static function addWechatUser(array $user)
    {
        return self::saveUser(
            [
                'nickname' => $user['nickname'],
                'avatar'   => $user['avatar'],
                'sex'      => $user['original']['sex']      ?? null,
                'city'     => $user['original']['city']     ?? null,
                'province' => $user['original']['province'] ?? null,
                'country'  => $user['original']['country']  ?? null,
                'language' => $user['original']['language'] ?? null,
                'unionid'  => $user['original']['unionid']  ?? null,
            ],
            $user['id'], // openid
            1
        );
    }

    /**
     * 添加或获取常观用户
     *
     * @param array $user
     * @return array|false
     */
    public static function addChangguanUser(array $user)
    {
        return self::saveUser(
            [
                'nickname' => $user['nickname'],
                'avatar'   => $user['avatar'],
                'truename' => $user['real_name']  ?? null,
                'phone'    => $user['mobile']     ?? null,
                'idcard'   => $user['identity']   ?? null,
                'sex'      => $user['gender']     ?? null,
                'unionid'  => $user['union_id']   ?? null,
            ],
            $user['openid'],
            2
        );
    }

    /**
     * 添加或获取常观工作台用户
     *
     * @param array $user
     * @return array|false
     */
    public static function addGongzuotaiUser(array $user)
    {
        return self::saveUser(
            [
                'nickname' => $user['true_name']  ?? null,
                'avatar'   => $user['avatar'],
                'truename' => $user['true_name']  ?? null,
                'phone'    => $user['mobile']     ?? null,
                'idcard'   => $user['identity']   ?? null,
                'sex'      => $user['gender']     ?? null,
                'unionid'  => $user['union_id']   ?? null,
                'departments'  => !empty($user['departments']) ? json_encode($user['departments'], JSON_UNESCAPED_UNICODE) : null,
                'department_name'   => $user['departments'][0]['name'] ?? null,
            ],
            $user['openid'],
            3
        );
    }

    /**
     * 核心保存逻辑
     *
     * @param array  $common   公共字段
     * @param string $openId   用户 open_id
     * @param int    $from     来源标记（1 = 微信，2 = 常观）
     * @return array|false
     */
    private static function saveUser(array $common, string $openId, int $from)
    {
        if (empty($openId)) {
            return false;
        }

        $now = time();

        try {
            $model = Db::transaction(function () use ($common, $openId, $from, $now) {

                // 悲观锁查
                $user = self::where('openid', $openId)
                            ->lock(true)
                            ->find();

                if ($user) {
                    // 同步更新已有用户
                    $user->save(array_merge($common, [
                        'login_count'     => $user->login_count + 1,
                        'last_login_time' => $now,
                    ]));
                } else {
                    // 创建新用户
                    $user = self::create(array_merge($common, [
                        'openid'          => $openId,
                        'from'            => $from,
                        'status'          => 1,
                        'login_count'     => 1,
                        'last_login_time' => $now,
                    ]));
                }

                return $user;
            });

            return $model ? $model->toArray() : false;
        } catch (\Exception $e) {
            Log::write("[User::saveUser] openid={$openId} from={$from} error: {$e->getMessage()}", 'error');
            return false;
        }
    }
}